package com.cfuture08.eweb4j.orm;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.cfuture08.eweb4j.cache.ORMConfigBeanCache;
import com.cfuture08.eweb4j.orm.config.bean.Property;
import com.cfuture08.util.ReflectUtil;
import com.cfuture08.util.StringUtil;

/**
 * 将从数据库查询出来的结果集映射成java对象
 * 
 * @author cfuture.aw
 * @since v1.a.0
 */
public class RowMapping {

	public static <T> List<T> mapRow(ResultSet rs, Class<T> clazz)
			throws Exception {
		List<T> list = new ArrayList<T>();
		T t = null;
		if (rs != null) {
			while (rs.next()) {
				t = clazz.newInstance();
				ReflectUtil ru = new ReflectUtil(t);
				for (Iterator<Property> it = ORMConfigBeanCache.get(clazz)
						.getProperty().iterator(); it.hasNext();) {
					Property p = it.next();
					String type = p.getType();
					Method m = ru.getMethod("set"
							+ StringUtil.toUpCaseFirst(p.getName()));
					if (m != null) {
						Object value = rs.getObject(p.getColumn());
						if (value != null) {
							String v = String.valueOf(value);
							if (v == null){
								v = "";
							}
							if ("int".equalsIgnoreCase(type)) {
								if ("".equals(v.trim())){
									v = "0";
								}
								m.invoke(t, Integer.parseInt(v));
							} else if ("long".equalsIgnoreCase(type)) {
								if ("".equals(v.trim())){
									v = "0";
								}
								m.invoke(t, Long.parseLong(v));
							} else if ("float".equalsIgnoreCase(type)) {
								if ("".equals(v.trim())){
									v = "0.0";
								}
								m.invoke(t, Float.parseFloat(v));
							}else if ("double".equalsIgnoreCase(type)) {
								if ("".equals(v.trim())){
									v = "0.0";
								}
								m.invoke(t, Float.parseFloat(v));
							} else if ("boolean".equalsIgnoreCase(type)) {
								boolean tb = false;
								if ("true".equals(v) || "1".equals(v)){
									tb = true;
								}
								m.invoke(t, tb);
							}else if ("string".equalsIgnoreCase(type)) {
								m.invoke(t, v);
							} else if (!"".equals(type)) {
								if (Date.class.isAssignableFrom(value.getClass())) {
									m.invoke(t, Date.class.cast(value)
											.toLocaleString());
								} else if (String.class.isAssignableFrom(value.getClass())){
									m.invoke(t, String.valueOf(value));
								}
							}
						}
					}
				}
				list.add(t);
			}
		}
		
		return list.isEmpty() ? null : list;
	}
}
